package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @description <p>管理员用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.admin.service.impl
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 登录校验
     *
     * @param paramMap
     * @return
     */
    @Override
    public Map<String, Object> loginCheck(Map<String, String> paramMap) {
        //1. 获取参数
        String name = paramMap.get("name");
        String password = paramMap.get("password");
        //2. 参数非空校验
        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            throw new LeadNewsException("用户名或密码错误!");
        }
        //3. 通过登录名查询用户信息
        AdUser adUser = query().eq("name", name).one();
        if(null == adUser){
            // 查不到数据则报错
            throw new LeadNewsException("用户名或密码错误!");
        }
        //4. 密码校验
        //4.1 密码加盐后进行MD5
        password += adUser.getSalt();
        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        //4.2 校验密码是否相同，不同则报错
        if(!adUser.getPassword().equals(encryptedPwd)){
            throw new LeadNewsException("用户名或密码错误!");
        }
        //5. 校验通过，生成token令牌
        String token = AppJwtUtil.createToken(adUser.getId().longValue());
        //6. 构建结果并返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", adUser);
        return result;
    }

//    public static void main(String[] args) {
//        String s = DigestUtils.md5DigestAsHex(("admin"+"123abc").getBytes());
//        System.out.println("s = " + s);
//    }
}
